package com.ruoyi.project.NH.farmer.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.project.NH.base_family_info.domain.BaseFamilyInfo;
import com.ruoyi.project.NH.base_family_info.mapper.BaseFamilyInfoMapper;
import com.ruoyi.project.NH.farmer.exception.DataException;
//import com.sun.corba.se.impl.io.ObjectStreamClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.NH.farmer.mapper.FarmerMapper;
import com.ruoyi.project.NH.farmer.domain.Farmer;
import com.ruoyi.project.NH.farmer.service.IFarmerService;

/**
 * 农户基本信息Service业务层处理
 *
 * @author 狗熊岭
 * @date 2023-07-24
 */
@Service
public class FarmerServiceImpl implements IFarmerService {
    @Autowired
    private FarmerMapper farmerMapper;
    @Autowired
    private BaseFamilyInfoMapper baseFamilyInfoMapper;

    /**
     * 查询农户基本信息
     *
     * @param id 农户基本信息主键
     * @return 农户基本信息
     */
    @Override
    public Farmer selectFarmerById(Integer id) {
        return farmerMapper.selectFarmerById(id);
    }

    /**
     * 查询农户基本信息列表
     *
     * @param farmer 农户基本信息
     * @return 农户基本信息
     */
    @Override
    public List<Farmer> selectFarmerList(Farmer farmer) {
        return farmerMapper.selectFarmerList(farmer);
    }

    /**
     * 新增农户基本信息
     *
     * @param farmer 农户基本信息
     * @return 结果
     */
    @Override
    public int insertFarmer(Farmer farmer) {
        farmer.setState(0);
        int flag = 0;
        if (farmer.getRegistrationTime() == null) {
            Date nowDate = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            try {
                date = formatter.parse(formatter.format(nowDate));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            farmer.setRegistrationTime(date);
        }
        /**
         * TODO
         * 在此处应该有一个判断：
         * 如果relationship是户主，继续判断：
         *      查找户主表看看有没有此farmer的户编号，若已存在，则不允许添加此农户，返回前端应显示已有农户不允许添加，return
         *                                      若不存在，则在农户户主表和农户表分别添加上此农户即可，并在前端返回添加成功。return
         *  如果relationship不是户主：
         *      1. 查找此farmer的fid对应的户主，在此户主的户主表中修改area（耕地面积）为+=当前新增农户的area  PS：这个操作不确定是否需要执行，有待商议
         *      2. 在农户表中查找是否有此farmer的idCard，若有则提示已有此农户，无法添加，前端对应展示即可
         *                                          若没有 则在农户表中添加此农户即可
         *      3.若fid不存在，则提醒该户不存在
         */
        /*
        因此根据以上逻辑，以下这行代码应该在此farmer的relationship为户主且户主表中没有此户编号才会新建户主对象，而不是什么判断都没有的情况下，随便添加一个农户
        都新建了一个户主对象
         */
        if (farmer.getRelationship() == 1) {
//            String fid=baseFamilyInfo.getFid();
//            OverviewDB overviewDB=new OverviewDB();
//            //设置表单中各个数据
//            overviewDB.setFid(fid);
//            overviewDB.setReportYear(2022);
//            overviewDB.setState(0);
//            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//            Date date=new Date();
//            overviewDB.setOpTime(sdf.format(date));
//            //管理员账号
//            User currentUser = ShiroUtils.getSysUser();
//            // 获取当前的用户名称
//            overviewDB.setUserId(currentUser.getUserId());
//            farmerMapper.insertFarmerForm(overviewDB);
            String fid = farmer.getFid();
            BaseFamilyInfo baseFamilyInfo1 = baseFamilyInfoMapper.selectBaseFamilyInfoByFid(fid);
            if (baseFamilyInfo1 == null) {
                BaseFamilyInfo baseFamilyInfo = new BaseFamilyInfo(farmer.getFid(), 1, farmer.getNatVillage(), farmer.getName(), farmer.getPhone(), farmerMapper.selectNumber(farmer.getFid()) + 1, farmer.getArea(), farmer.getFamilyType(), 0);
                flag = (baseFamilyInfoMapper.insertBaseFamilyInfo(baseFamilyInfo) + farmerMapper.insertFarmer(farmer));
            }
            else if(baseFamilyInfo1 != null&&baseFamilyInfo1.getState()==0){
                throw new DataException("该户已存在户主！");
            }
            else if(baseFamilyInfo1 != null&&baseFamilyInfo1.getState()==1){
                throw new DataException("该户已经销户，请使用其他户编号！");
            }
        }
        if (farmer.getRelationship() != 1) {
            String fid = farmer.getFid();
            BaseFamilyInfo baseFamilyInfo1 = baseFamilyInfoMapper.selectBaseFamilyInfoByFid(fid);
            if (baseFamilyInfo1 != null &&baseFamilyInfo1.getState()==0) {
                String IdCard = farmer.getIdCard();
                //通过前端传过来的idCard来找数据库已存的对象
                Farmer farmer1 = farmerMapper.selectFarmByIdCard(IdCard);
                if (farmer1 == null) {
//                    不是户主不需要新建一户
//                    BaseFamilyInfo baseFamilyInfo = new BaseFamilyInfo(farmer.getFid(),0,farmer.getNatVillage(),farmer.getName(),farmer.getPhone(),farmerMapper.selectNumber(farmer.getFid())+1,farmer.getArea(),farmer.getFamilyType(),0);
                    Integer num = farmerMapper.selectNumber(farmer.getFid()) + 1;
                    flag = farmerMapper.insertFarmer(farmer) + baseFamilyInfoMapper.updateBaseFamilyInfoNum(fid, num);
                }
                else {
//                    if (farmer1.getState() == 1) {
//                        Integer id = farmer1.getId();
//                        //返回值flag作为ajax发送请求的结果，为大于0时表明成功，所以别忘记给flag赋值
//                        flag = farmerMapper.updateFarmerByIdCard(id, farmer);
//                    } else
//                        {
                        throw new DataException("该户已存在该人员！");
//                    }
                }
            }
            else if (baseFamilyInfo1 != null &&baseFamilyInfo1.getState()==1){
                throw new DataException("该户已注销，无法加入新的户成员！");
            }
            else if(baseFamilyInfo1 == null){
                throw new DataException("该户不存在！");
            }
        }
        return flag;
    }

    /**
     * 修改农户基本信息
     *
     * @param farmer 农户基本信息
     * @return 结果
     */
    @Override
    public int updateFarmer(Farmer farmer) {
        int flag=0;
        //既然有该farm并且有id说明肯定没有被注销，oldfarm一定存在state一定为0
        Farmer oldFarmer=farmerMapper.selectFarmerById(farmer.getId());
        String oldfid=oldFarmer.getFid();
        String phone=farmer.getPhone();
        BigDecimal area=farmer.getArea();
        Integer familyType=farmer.getFamilyType();
        String newfid=farmer.getFid();
            //只有户主才可以改户编号，要是改变户编号，所有成员户编号都需要改变
        if(oldFarmer.getRelationship()==1&&farmer.getRelationship()==1&&oldfid.equals(newfid)){
            flag=baseFamilyInfoMapper.updateBaseFamilyInfoByEdit(phone,area,familyType,oldfid)+farmerMapper.updateFarmer(farmer);
        }
        else if(oldFarmer.getRelationship()==1&&farmer.getRelationship()==1&&!newfid.equals(oldfid)&&baseFamilyInfoMapper.selectBaseFamilyInfoByFid(newfid)==null){
            flag=baseFamilyInfoMapper.updateBaseFamilyInfoByEdit1(phone,area,familyType,oldfid,newfid)+farmerMapper.updateFarmer(farmer)+farmerMapper.updateFarmerMemberByFid(oldfid,newfid);
        }
        else if(oldFarmer.getRelationship()==1&&farmer.getRelationship()==1&&!newfid.equals(oldfid)&&baseFamilyInfoMapper.selectBaseFamilyInfoByFid(newfid)!=null&&farmer.getState()==0){
            throw new DataException("该户编号已存在，请尝试其他户编号");
        }
        else if(oldFarmer.getRelationship()==1&&farmer.getRelationship()==1&&!newfid.equals(oldfid)&&baseFamilyInfoMapper.selectBaseFamilyInfoByFid(newfid)!=null&&farmer.getState()==1){
            throw new DataException("该户编号已存在并且已经注销，请尝试其他户编号");
        }
        else if(oldFarmer.getRelationship()==1&&farmer.getRelationship()!=1){
            throw new DataException("请转移户主之后再进行操作");
        }
        else if(oldFarmer.getRelationship()!=1&&farmer.getRelationship()!=1){
            flag=farmerMapper.updateFarmer(farmer);
        }
        else if(oldFarmer.getRelationship()!=1&&farmer.getRelationship()==1){
            throw new DataException("请转移户主之后再进行操作");
        }
        return flag;
    }

//    /**
//     * 批量删除农户基本信息
//     *
//     * @param ids 需要删除的农户基本信息主键
//     * @return 结果
//     */
//    @Override
//    public int deleteFarmerByIds(Integer[] ids)
//    {
//        return farmerMapper.deleteFarmerByIds(ids);
//    }

    /**
     * 删除农户基本信息信息。不为户主
     *
     * @param id 农户基本信息主键
     * @return 结果
     */
    @Override
    public int deleteFarmerById(Integer id)
    {
        int flag = 0;
        Farmer farmer=farmerMapper.selectFarmerById(id);
        int number = farmerMapper.selectNumber(farmer.getFid());
        Integer relationship=farmer.getRelationship();
        if(relationship!=1) {
            //不论是否为户主，户人口数都需要减一
            flag = farmerMapper.logoutFarmerById(id) + baseFamilyInfoMapper.logoutNumBaseFamilyInfoByFid(farmer.getFid());
        }
        else{
            if(number==1){
             flag = farmerMapper.logoutFarmerById(id) + baseFamilyInfoMapper.logoutNumBaseFamilyInfoByFid(farmer.getFid())+baseFamilyInfoMapper.logoutStateBaseFamilyInfoByFid(farmer.getFid());
            }
            else{
                throw new DataException("需要进行户主转移");
            }
        }
        return flag;
    }
//    public int deleteFarmerById(Integer id) {
//        int flag = 0;
//        Farmer farmer = farmerMapper.selectFarmerById(id);
//        //不论是否为户主，户人口数都需要减一
//        flag = farmerMapper.logoutFarmerById(id) + baseFamilyInfoMapper.logoutNumBaseFamilyInfoByFid(farmer.getFid());
//        return flag;
//    }

    /**
     * 删除农主基本信息信息。为户主
     *
     * @param id 农户基本信息主键
     * @return 结果
     */
    @Override
    public int deleteHouseholderById(Integer id) {
        Farmer farmer = farmerMapper.selectFarmerById(id);
        int number = farmerMapper.selectNumber(farmer.getFid());
        if (number == 1) {
            farmerMapper.logoutFarmerById(id);
            baseFamilyInfoMapper.logoutNumBaseFamilyInfoByFid(farmer.getFid());
            baseFamilyInfoMapper.logoutStateBaseFamilyInfoByFid(farmer.getFid());
        }
      return number;//返回值为一即提示删除成功即可，返回值大于等于一，进行转移户主操作
    }

    /**
     * 转移户主
     *
     * @param fid,oldName,newName,str 参数
     * @return 结果
     */
    @Override
    public int transferHouseholder(String fid,String oldName, String newName,String str)
    {
        //当一户多个农户时判断是否选择多个新户主
        int house_hold = 0;
        Farmer farmer = new Farmer();
        String[] strArr = str.split(",");
        farmer.setFid(fid);
        farmer.setName(newName);
//        查询当前农户表里所有的农户信息
        List<Farmer> list = farmerMapper.selectFarmerList(farmer);
        farmer.setId(list.get(0).getId());

        Farmer[] farmers = new Farmer[10];
        int index = 0;
        for (int i=0;i<(strArr.length)/2;i++){
            Farmer ff = new Farmer();
            ff.setFid(fid);
            ff.setId(Integer.valueOf(strArr[index]));
            ff.setRelationship(Integer.valueOf(strArr[++index]));
            index++;
            farmers[i] = ff;
            //保证只有一个与户主关系为户主
            if (ff.getRelationship()==1){
                house_hold ++;
                //保证新户主姓名与户主关系统一
                if (ff.getId()!=farmer.getId()){
                    return 0;
                }
            }
        }
        if (house_hold > 1){
            return 0;
        }
        //如果与户主关系中没有户主
        if (house_hold == 0){
            return 0;
        }

        int flag = 0;
        BaseFamilyInfo baseFamilyInfo = new BaseFamilyInfo();

        baseFamilyInfo.setFid(fid);
        baseFamilyInfo.setName(newName);
        int num = baseFamilyInfoMapper.selectBaseFamilyInfoByFid(fid).getNum();
        num = num-1;
        baseFamilyInfo.setNum(num);
        flag += baseFamilyInfoMapper.updateBaseFamilyInfo(baseFamilyInfo);
        for (int i=0;i<num;i++){
            Farmer farmer1 = farmers[i];
            flag += farmerMapper.updateFarmer(farmer1);
        }
        flag += farmerMapper.updateHouseHoldState(fid,oldName);
        return flag;
    }

    /**
     * 查询家庭其他成员
     *
     * @param fid 户id
     * @return 农户信息集合
     */
    public List<Farmer> selectMember(String fid){
        return farmerMapper.selectMember(fid);
    }
}
